<template>
  <el-dialog :title="title" :visible="visible" @close="handleDialogClose" width="600px">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="100px"
      class="form"
    >
      <el-form-item label="用户姓名:" prop="userName">
        <el-input class="form-item" v-model="form.userName" placeholder="请输入用户姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input class="form-item" v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱:" prop="email">
        <el-input class="form-item" v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="性别:">
        <el-select v-model="form.sex" placeholder="请选择性别" class="form-item">
          <el-option label="未知" :value="0"></el-option>
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色:" prop="roleIds">
        <el-select
          v-model="form.roleIds"
          multiple
          value-key="roleId"
          placeholder="请选择角色"
          class="form-item"
        >
          <el-option
            v-for="item of roleList"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门:" prop="departmentId">
        <el-cascader
          v-model="form.departmentId"
          :options="departmentList"
          :props="props"
          clearable
          class="form-item"
        />
      </el-form-item>
      <el-form-item label="账号状态:">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UserService from '../../../../service/user'
import RoleService from '../../../../service/role'
import DepartmentService from '../../../../service/department'

export default {
  props: {
    title: {
      type: String,
      required: true,
      default: () => ''
    },
    show: {
      type: Boolean,
      required: true,
      default: () => false
    },
    data: {
      type: Object,
      required: false,
      default: () => {}
    }
  },
  data() {
    // 手机号验证
    const checkPhone = async (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      } else {
        const result = await this.getIsExistsByKeyword(value)
        if (result.data) {
          return callback(new Error('该手机号已被注册'))
        }
        callback()
      }
    }

    // 邮箱验证
    const checkEmail = async (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      // 邮箱非必填 为空直接通过验证
      if (value === '') {
        return callback()
      }
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的邮箱'))
      } else {
        const result = await this.getIsExistsByKeyword(value)
        if (result.data) {
          return callback(new Error('该邮箱已被注册'))
        }
        callback()
      }
    }

    return {
      visible: false,
      roleList: [],
      departmentList: [],
      props: {
        value: 'departmentId',
        label: 'departmentName',
        emitPath: false
      },
      form: {
        userId: '',
        userName: '',
        phone: '',
        email: '',
        sex: 0,
        roleIds: [],
        departmentId: '',
        status: 0
      },
      rules: {
        userName: { required: true, message: '请输入用户名', trigger: 'blur' },
        phone: { required: true, validator: checkPhone, trigger: 'blur' },
        email: { validator: checkEmail, trigger: 'blur' },
        roleIds: { required: true, message: '请选择角色', trigger: 'change' },
        departmentId: {
          required: true,
          message: '请选择部门',
          trigger: 'change'
        }
      }
    }
  },
  methods: {
    // 处理Dialog关闭事件
    handleDialogClose() {
      this.$emit('update:show')
      this.form = {
        userId: '',
        userName: '',
        phone: '',
        email: '',
        sex: 0,
        roleIds: [],
        departmentId: '',
        status: 0
      }
      this.$refs.form.resetFields()
    },
    // 判断手机号、邮箱是否已被注册
    getIsExistsByKeyword(keyword) {
      return UserService.getIsExistsByKeyword(keyword, this.form.userId)
    },
    // 获取角色列表
    getRoles() {
      RoleService.getRoles().then(res => {
        this.roleList = res.data
      })
    },
    // 获取部门列表
    getDepartments() {
      DepartmentService.getDepartmentsByDepartmentName().then(res => {
        this.departmentList = this.recursionClearChildren(res.data)
      })
    },
    // 递归清除为空的children
    recursionClearChildren(list) {
      let arr = []
      list.forEach(item => {
        if (item.children.length === 0) {
          delete item.children
        } else {
          item.children = this.recursionClearChildren(item.children)
        }
        arr.push(item)
      })
      return arr
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.userId) {
            // 清空 department 属性
            delete this.form.department
            // 清空 roles 属性
            delete this.form.roles
            // 情空 permissions 属性
            delete this.form.permissions

            UserService.updateUser(this.form).then(res => {
              // 提示
              this.$message.success(res.message)
              // 关闭Dialog
              this.visible = false
              // 派发事件刷新Table
              this.$emit('success', null)
            })
          } else {
            UserService.insertUser(this.form).then(res => {
              // 提示
              this.$message.success(res.message)
              // 关闭Dialog
              this.visible = false
              // 派发事件刷新Table
              this.$emit('success', 1)
            })
          }
        }
      })
    }
  },
  mounted() {
    this.getRoles()
    this.getDepartments()
  },
  watch: {
    show(value) {
      this.visible = value
    },
    data(value) {
      this.form = value || {
        userId: '',
        userName: '',
        phone: '',
        email: '',
        sex: 0,
        roleIds: [],
        departmentId: '',
        status: 0
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.form
  margin 0 30px
  .form-item
    width 300px
</style>
